﻿using FangPage.Admin.Model;
using FangPage.Common;
using FangPage.Core;
using FangPage.Data;
using FangPage.User;
using FangPage.User.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FangPage.Admin.Controller
{
    public class menu_get : UserController
    {
        protected List<MenuInfo> menulist = new List<MenuInfo>();

        protected RoleInfo roleinfo = new RoleInfo();

        public override void Controller()
        {
            string parentid = FPRequest.GetString("parentid");

            roleinfo = DbHelper.ExcuteModel<RoleInfo>(authinfo.roleid);

            SqlParam sqlparam = DbHelper.MakeOrderBy("display", OrderBy.ASC);

            menulist = DbHelper.ExcuteList<MenuInfo>(sqlparam);

            List<FPObject> navlist = GetMenuChildren(parentid);

            FPResponse.WriteData(navlist);
        }

        /// <summary>
        /// 获取菜单数据
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<FPObject> GetMenuChildren(string parentid)
        {
            List<FPObject> menus_data = new List<FPObject>();

            List<MenuInfo> children = menulist.Where(item => item.parentid == parentid).ToList();

            foreach (var item in children)
            {
                if (FPArray.InArray(item.id, roleinfo.menus) >= 0)
                {
                    FPObject obj = new FPObject();

                    obj["id"] = item.id;
                    obj["title"] = item.name;
                    obj["href"] = item.url;
                    obj["spread"] = false;
                    obj["icon"] = item.icon;
                    obj["pid"] = item.parentid;

                    if(!parentid.IsNullOrEmpty())
                    {
                        List<FPObject> menus_children = GetMenuChildren(item.id);

                        obj["children"] = menus_children;
                    }
                    
                    menus_data.Add(obj);
                }
            }

            return menus_data;
        }
    }
}
